package com.sf.osms.dep.processor.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import com.sf.osms.dep.domain.Agent;

public class CollectionUtil {

	/**
	 * 进行mapRule字段的解析
	 * @param formatStr 对应规则字符串
	 * @return
	 */
	public static Map<String,String> formatStrToMap(String formatStr){
		
		if(StringUtils.isEmpty(formatStr)){
			return null;
		}
		Map<String,String> map = new HashMap<String, String>();
		String[] fieldMaps = formatStr.split("!");
		for (String fieldMap : fieldMaps) {
			String[] fields = fieldMap.split(",");
			if(fields[1].contains("&")){
				String[] strs = fields[1].split("&");
				for (String str : strs) {
					map.put(str, fields[0]);
				}
				
			}else{
				map.put(fields[1],fields[0]);
			}
		}
		
		return map;
		
	}
	
	/**
	 * 进行mapRule的字段解析
	 * @param formatStr
	 * @return
	 */
	public static Map<String,String> formatRuleToMap(String formatStr){
		
		if(StringUtils.isEmpty(formatStr)){
			return null;
		}
		Map<String,String> map = new HashMap<String, String>();
		String[] fieldMaps = formatStr.split("!");
		for (String fieldMap : fieldMaps) {
			String[] fields = fieldMap.split(",");
			if(null != fields && fields.length == 2){
				map.put(fields[0],fields[1]);
			}
		}
		
		return map;
	}
	
	public static boolean isEmpty(Collection list){
		if(null == list || list.isEmpty()){
			return true;
		}else{
			return false;
		}
	}
	
	/**
	 * 进行集合中去除空白字符操作
	 * @param list
	 * @return
	 */
	public static  List<String> removeBlankElement(List<String> list){
		List<String> resultList = new ArrayList<String>();
		if(!isEmpty(list)){
			for(String s:list){
				if(StringUtils.isNotBlank(s)){
					resultList.add(s);
				}
			}
		}
		return resultList;
	}
	
	public static void strListToFile(List<String> list, String filePath){
		    Set<String> set = new HashSet<String>();
		    set.addAll(list);
			FileWriter fw = null;
			BufferedWriter bw = null;
			try {
				File file = new File(filePath);
				if(!file.exists()){
					try {
						file.createNewFile();
					}catch (IOException e) {
						e.printStackTrace();
					}
					
				}
				fw = new FileWriter(filePath, false);
				bw = new BufferedWriter(fw);
				for(String fileName:set){
					bw.write(fileName);
					bw.newLine();
					bw.flush(); //将数据更新至文件
				}
				bw.close();
				fw.close();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try{
					if(bw!=null){
						bw.close();
					}
					if(fw!=null){
					   fw.close();
					}
				}catch(Exception e){
					e.printStackTrace();
				}
				
			}
			

	}
	
	/**
	 * 罗列指定目录下所有的文件名
	 * @param filePath
	 * @return
	 */
	public static List<String> strFileToList(String filePath){

		List<String> list = new ArrayList<String>();
		//这里参数为文件路径，可以读取全部常见类型文件
		FileReader reader = null;
		BufferedReader br = null;
		try {

			
			reader = new FileReader(filePath);
			br = new BufferedReader(reader);
			String str = null;
			while((str = br.readLine()) != null)
			{
				list.add(str);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			//关闭读写流
			try {
				if(br!=null){
					br.close();
				}
				if(reader!=null){
					reader.close();
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return list;
	}
	
	public static String listFileToFileNameArray(List<File> files){
		StringBuilder sb = new StringBuilder();
		if(CollectionUtil.isEmpty(files)){
			return null;
		}
		
		for (File file : files) {
			sb.append("     {" + file.getAbsolutePath() +"},");
		}
		
		return sb.toString();
	}
	
	/**
	 * 将对象转化为Map，若是String数组，则key为数组中的位置,若是普通的javabean对象就是将其属性名作为key
	 * @return
	 */
	public static Map<String,String> transferObjectToMap(Object obj){
		Map<String,String> map = new HashMap<String, String>();
		if(obj instanceof String[]){
			String[] strs = (String[]) obj;
			
			for(int i=0;i<strs.length;i++){	
				map.put(String.valueOf(i+1), strs[i]);
			}
		}else{
			Class clazz = obj.getClass();
			Field[] fields = clazz.getDeclaredFields();
			for (Field field : fields) {
				if(Field.PUBLIC == field.getModifiers()){
					continue;
				}
				
				Object fieldVal = ReflectUtils.getFieldValue(obj, field.getName());
				if(null != fieldVal && fieldVal instanceof String){
					
					String fieldStr = (String) fieldVal;
					if(!StringUtils.isBlank(fieldStr)){
						map.put(field.getName(),fieldStr);
					}
				}
				}
			}
		
		
		return map;
	}
	
	/**
	 * 将router中字段和属性对应起来
	 * @param filedRule key--Router表中字段，value--对应解析出来对象中的字段(若为String[],则为列数，列从1开始)
	 * @param fieldValue key--解析出来的字段（若为String[],则为列数，从1开始），value--解析出来的值（String）
	 * @return router字段对应的值（String） 需要具体的处理
	 */
	public static Map<String,String> getFileldAndValueMap(Map<String,String> fieldRule,Map<String,String> fieldValue){
		
		Set<Entry<String, String>> entrySet = fieldRule.entrySet();
		Iterator<Entry<String, String>> iterator = entrySet.iterator();
		while (iterator.hasNext()) {
			Entry<String, String> next = iterator.next();
			String value = next.getValue();
			String fieldVal = fieldValue.get(value);
			if(!StringUtils.isBlank(fieldVal)){
				next.setValue(fieldVal);
			}else{
				next.setValue(""); //若没有对应的字段值，则为""
			}
		}
		
		return fieldRule;
	}
	
	
	public static <T> List<List<T>> splitList(List<T> resList,int count){
	    
	    if(resList==null ||count<1)
	      return  null ;
	    List<List<T>> ret=new ArrayList<List<T>>();
	    int size=resList.size();
	    if(size<=count){ //数据量不足count指定的大小
	      ret.add(resList);
	    }else{
	      int pre=size/count;
	      int last=size%count;
	      //前面pre个集合，每个大小都是count个元素
	      for(int i=0;i<pre;i++){
	        List<T> itemList=new ArrayList<T>();
	        for(int j=0;j<count;j++){
	          itemList.add(resList.get(i*count+j));
	        }
	        ret.add(itemList);
	      }
	      //last的进行处理
	      if(last>0){
	        List<T> itemList=new ArrayList<T>();
	        for(int i=0;i<last;i++){
	          itemList.add(resList.get(pre*count+i));
	        }
	        ret.add(itemList);
	      }
	    }
	    return ret;
	    
	  }
	public static void main(String[] args) {
		String str = "8&9";
		String[] strs = str.split("&");
		Agent agentInfo = new Agent();
		agentInfo.setUploadPath("/test");
		agentInfo.setBackPath("/test_build/backup");
		agentInfo.setId(1L);
		agentInfo.setName("日本代理");
		Map<String,String> map = CollectionUtil.transferObjectToMap(agentInfo);
		System.out.println(map);
	}

	public static Map<String,String> getFieldAndValueMap(Map<String, String> newMapRules,
			String lineStr) {
		Set<Entry<String, String>> entrySet = newMapRules.entrySet();
		Iterator<Entry<String, String>> iterator = entrySet.iterator();
		while (iterator.hasNext()) {
			Entry<String, String> next = iterator.next();
			String columnRule = next.getValue();
			String[] splits = columnRule.split(RouterConstants.AGENT_FILE_MAP_RULE_NUM);
			if(splits.length == 2){
				String substring = lineStr.substring(Integer.valueOf(splits[0]), Integer.valueOf(splits[1]));
				next.setValue(substring);
			}else{
				next.setValue("");
			}
		}
		return newMapRules;
	}
}
